document.addEventListener('DOMContentLoaded', function() {
    // 上传相关的DOM元素
    const singleEyeUpload = document.getElementById('single-eye-upload');
    const leftEyeUpload = document.getElementById('left-eye-upload');
    const rightEyeUpload = document.getElementById('right-eye-upload');
    
    const singleImageInput = document.getElementById('single-image-input');
    const leftImageInput = document.getElementById('left-image-input');
    const rightImageInput = document.getElementById('right-image-input');
    
    const singleFolderInput = document.getElementById('single-folder-input');
    const leftFolderInput = document.getElementById('left-folder-input');
    const rightFolderInput = document.getElementById('right-folder-input');
    
    const singleImagePreview = document.getElementById('single-image-preview');
    const leftEyePreview = document.getElementById('left-eye-preview');
    const rightEyePreview = document.getElementById('right-eye-preview');
    
    const batchModeSingle = document.getElementById('batch-mode-single');
    const batchModeBoth = document.getElementById('batch-mode-both');
    
    // 批量模式切换处理
    batchModeSingle.addEventListener('change', function() {
        const singleUploadMode = singleEyeUpload.querySelector('.single-upload-mode');
        const batchUploadMode = singleEyeUpload.querySelector('.batch-upload-mode');
        
        singleUploadMode.classList.toggle('d-none', this.checked);
        batchUploadMode.classList.toggle('d-none', !this.checked);
        
        // 重置预览
        resetPreview(singleImagePreview);
        
        // 更新开始按钮状态
        updateStartButton();
    });
    
    batchModeBoth.addEventListener('change', function() {
        const leftSingleMode = leftEyeUpload.querySelector('.single-upload-mode');
        const leftBatchMode = leftEyeUpload.querySelector('.batch-upload-mode');
        const rightSingleMode = rightEyeUpload.querySelector('.single-upload-mode');
        const rightBatchMode = rightEyeUpload.querySelector('.batch-upload-mode');
        
        leftSingleMode.classList.toggle('d-none', this.checked);
        leftBatchMode.classList.toggle('d-none', !this.checked);
        rightSingleMode.classList.toggle('d-none', this.checked);
        rightBatchMode.classList.toggle('d-none', !this.checked);
        
        // 重置预览
        resetPreview(leftEyePreview);
        resetPreview(rightEyePreview);
        
        // 更新开始按钮状态
        updateStartButton();
    });
    
    // 单张图片上传点击处理
    document.getElementById('single-preview-container').addEventListener('click', function() {
        singleImageInput.click();
    });
    
    document.getElementById('left-preview-container').addEventListener('click', function() {
        leftImageInput.click();
    });
    
    document.getElementById('right-preview-container').addEventListener('click', function() {
        rightImageInput.click();
    });
    
    // 文件夹上传点击处理
    singleEyeUpload.querySelector('.folder-upload-container').addEventListener('click', function() {
        singleFolderInput.click();
    });
    
    leftEyeUpload.querySelector('.folder-upload-container').addEventListener('click', function() {
        leftFolderInput.click();
    });
    
    rightEyeUpload.querySelector('.folder-upload-container').addEventListener('click', function() {
        rightFolderInput.click();
    });
    
    // 文件选择处理
    singleImageInput.addEventListener('change', function() {
        handleFileSelect(this, singleImagePreview);
    });
    
    leftImageInput.addEventListener('change', function() {
        handleFileSelect(this, leftEyePreview);
    });
    
    rightImageInput.addEventListener('change', function() {
        handleFileSelect(this, rightEyePreview);
    });
    
    // 文件夹选择处理
    singleFolderInput.addEventListener('change', function() {
        handleFolderSelect(this, 'single');
    });
    
    leftFolderInput.addEventListener('change', function() {
        handleFolderSelect(this, 'left');
    });
    
    rightFolderInput.addEventListener('change', function() {
        handleFolderSelect(this, 'right');
    });
    
    // 拖放功能
    setupDragAndDrop(singleEyeUpload);
    setupDragAndDrop(leftEyeUpload);
    setupDragAndDrop(rightEyeUpload);
    
    // 处理文件选择
    function handleFileSelect(input, preview) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            if (validateImageFile(file)) {
                displayPreview(file, preview);
                updateStartButton();
            }
        }
    }
    
    // 处理文件夹选择
    function handleFolderSelect(input, type) {
        if (input.files && input.files.length > 0) {
            const files = Array.from(input.files).filter(file => 
                file.type.match('image/(jpeg|png|jpg)'));
            
            if (files.length === 0) {
                showAlert('警告', '文件夹中没有有效的图片文件！');
                return;
            }
            
            // 显示选择的文件数量
            showAlert('成功', `已选择 ${files.length} 张图片，点击"开始分析"按钮开始处理`);
            
            // 更新UI，显示已选择文件夹的状态
            updateFolderSelectionUI(input, files.length);
            
            if (type === 'left' || type === 'right') {
                // 检查左右眼文件夹的匹配性
                validateBothEyesFolders();
            }
            
            updateStartButton();
        }
    }
    
    // 添加新函数：更新文件夹选择UI
    function updateFolderSelectionUI(input, fileCount) {
        // 找到对应的容器
        let container;
        if (input === singleFolderInput) {
            container = singleEyeUpload.querySelector('.folder-upload-container');
        } else if (input === leftFolderInput) {
            container = leftEyeUpload.querySelector('.folder-upload-container');
        } else if (input === rightFolderInput) {
            container = rightEyeUpload.querySelector('.folder-upload-container');
        }
        
        if (container) {
            // 更新内容以显示已选择的文件数量
            container.innerHTML = `
                <i class="bi bi-folder-check text-success"></i>
                <p>已选择 ${fileCount} 张图片</p>
                <small class="text-muted">点击更改</small>
            `;
            container.classList.add('selected');
        }
    }
    
    // 当复位按钮被点击时，重置文件夹选择UI
    function resetFolderSelectionUI() {
        const containers = document.querySelectorAll('.folder-upload-container');
        containers.forEach(container => {
            container.innerHTML = `
                <i class="bi bi-folder-plus"></i>
                <p>选择图片文件夹</p>
            `;
            container.classList.remove('selected');
        });
    }
    
    // 验证双眼文件夹匹配
    function validateBothEyesFolders() {
        if (!leftFolderInput.files.length || !rightFolderInput.files.length) {
            return false;
        }
        
        const leftFiles = Array.from(leftFolderInput.files)
            .filter(f => f.type.match('image/(jpeg|png|jpg)'))
            .map(f => f.name);
        const rightFiles = Array.from(rightFolderInput.files)
            .filter(f => f.type.match('image/(jpeg|png|jpg)'))
            .map(f => f.name);
        
        if (leftFiles.length !== rightFiles.length) {
            showAlert('错误', '左右眼图片数量不匹配！');
            return false;
        }
        
        // 检查文件名是否匹配
        const mismatchedFiles = leftFiles.filter(f => !rightFiles.includes(f));
        if (mismatchedFiles.length > 0) {
            showAlert('错误', '左右眼图片文件名不匹配！');
            return false;
        }
        
        return true;
    }
    
    // 设置拖放功能
    function setupDragAndDrop(container) {
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            container.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            container.addEventListener(eventName, () => {
                container.classList.add('drag-over');
            });
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            container.addEventListener(eventName, () => {
                container.classList.remove('drag-over');
            });
        });
        
        container.addEventListener('drop', (e) => {
            const isBatchMode = container.querySelector('.batch-upload-mode').classList.contains('d-none') === false;
            const files = e.dataTransfer.files;
            
            if (isBatchMode) {
                // 处理文件夹拖放
                handleFolderDrop(container, files);
            } else if (files.length > 0) {
                // 处理单文件拖放
                handleFileDrop(container, files[0]);
            }
        });
    }
    
    // 处理文件拖放
    function handleFileDrop(container, file) {
        if (validateImageFile(file)) {
            let input, preview;
            
            if (container === singleEyeUpload) {
                input = singleImageInput;
                preview = singleImagePreview;
            } else if (container === leftEyeUpload) {
                input = leftImageInput;
                preview = leftEyePreview;
            } else if (container === rightEyeUpload) {
                input = rightImageInput;
                preview = rightEyePreview;
            }
            
            // 创建新的 FileList 对象
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(file);
            input.files = dataTransfer.files;
            
            displayPreview(file, preview);
            updateStartButton();
        }
    }
    
    // 处理文件夹拖放
    function handleFolderDrop(container, files) {
        let input, type;
        
        if (container === singleEyeUpload) {
            input = singleFolderInput;
            type = 'single';
        } else if (container === leftEyeUpload) {
            input = leftFolderInput;
            type = 'left';
        } else if (container === rightEyeUpload) {
            input = rightFolderInput;
            type = 'right';
        }
        
        const validFiles = Array.from(files).filter(file => 
            file.type.match('image/(jpeg|png|jpg)'));
        
        if (validFiles.length === 0) {
            showAlert('警告', '未找到有效的图片文件！');
            return;
        }
        
        // 创建新的 FileList 对象
        const dataTransfer = new DataTransfer();
        validFiles.forEach(file => dataTransfer.items.add(file));
        input.files = dataTransfer.files;
        
        if (type === 'left' || type === 'right') {
            validateBothEyesFolders();
        }
        
        updateStartButton();
    }
    
    // 验证图片文件
    function validateImageFile(file) {
        if (!file.type.match('image/(jpeg|png|jpg)')) {
            showAlert('错误', '请选择有效的图片文件 (JPG, JPEG, PNG)');
            return false;
        }
        return true;
    }
    
    // 显示图片预览
    function displayPreview(file, preview) {
        const reader = new FileReader();
        reader.onload = (e) => {
            preview.src = e.target.result;
            preview.classList.remove('d-none');
            const placeholder = preview.parentElement.querySelector('.upload-placeholder');
            if (placeholder) {
                placeholder.classList.add('d-none');
            }
        };
        reader.readAsDataURL(file);
    }
    
    // 重置预览
    function resetPreview(preview) {
        if (preview) {
            preview.src = '';
            preview.classList.add('d-none');
            const placeholder = preview.parentElement.querySelector('.upload-placeholder');
            if (placeholder) {
                placeholder.classList.remove('d-none');
            }
        }
    }
    
    // 更新开始按钮状态
    function updateStartButton() {
        const startButton = document.getElementById('start-analysis');
        const activeTab = document.querySelector('.tab-pane.active');
        let isValid = false;
        
        if (activeTab.id === 'single-eye') {
            isValid = batchModeSingle.checked 
                ? singleFolderInput.files.length > 0 
                : singleImageInput.files.length > 0;
        } else if (activeTab.id === 'both-eyes') {
            isValid = batchModeBoth.checked
                ? (leftFolderInput.files.length > 0 && rightFolderInput.files.length > 0 && validateBothEyesFolders())
                : (leftImageInput.files.length > 0 && rightImageInput.files.length > 0);
        }
        
        startButton.disabled = !isValid;
    }
    
    // 显示警告提示
    function showAlert(title, message) {
        // 创建警告提示元素
        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-warning alert-dismissible fade show';
        alertDiv.innerHTML = `
            <strong>${title}：</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // 创建或获取警告容器
        let alertContainer = document.getElementById('alert-container');
        if (!alertContainer) {
            alertContainer = document.createElement('div');
            alertContainer.id = 'alert-container';
            alertContainer.className = 'position-fixed top-0 end-0 p-3';
            alertContainer.style.zIndex = '1050';
            document.body.appendChild(alertContainer);
        }
        
        // 添加警告到容器
        alertContainer.appendChild(alertDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            const alert = bootstrap.Alert.getOrCreateInstance(alertDiv);
            alert.close();
        }, 3000);
    }
}); 